package gaboli.common.utils;

import java.util.HashMap;
import java.util.Map;

/**
 * Utility method for getting Mappings from query-delimited strings.
 *
 * @author @author C. Burrell deltafront@gmail.com
 */
public class MappingUtils
{
    /**
     * Returns a mapping of all key=value pairs in the query string. The following assumptions are made when using
     * this method:
     * - '&' is used to separate each key=value pairing.
     * - '=' is used to separate the key from the value in each key=value pair.
     *
     * @param queryString String that contains key=value pairs.
     * @return Mapping of all key=value pairs in the query string.
     * @since 1.0
     */
    public Map<String, String> getMappings( String queryString )
    {
        return getMappings( queryString, "&", "=" );
    }

    /**
     * Returns a mapping of all key=value pairs in the query string. This method assumes that '=' is used
     * to separate the key from teh value in each key=value pair.
     *
     * @param queryString   String that contains key=value pairs.
     * @param termDelimiter String that represents delimiter that separates key-value pairs.
     * @return Mapping of all key=value pairs in the query string.
     * @since 1.0
     */
    public Map<String, String> getMappings( String queryString, String termDelimiter )
    {
        return getMappings( queryString, termDelimiter, "=" );
    }

    /**
     * Returns a mapping of all key=value pairs in the query string.
     *
     * @param queryString       String that contains key=value pairs.
     * @param termDelimiter     String that represents delimiter that separates key-value pairs.
     * @param equalityDelimiter String that represents delimiter that separates the key from the value
     *                          in each key=value pair.
     * @return Mapping of all key=value pairs in the query string.
     * @since 1.0
     */
    public Map<String, String> getMappings( String queryString, String termDelimiter, String equalityDelimiter )
    {
        Map<String, String> mapping = new HashMap<String, String>();
        String[] terms = queryString.split( termDelimiter );
        for( String term : terms )
        {
            String[] keyValuePair = term.split( equalityDelimiter );
            mapping.put( keyValuePair[ 0 ], keyValuePair[ 1 ] );
        }
        return mapping;
    }
}